package com.dcits.ftz.service;

import com.dcits.exception.BusinessException;
import com.dcits.exception.ErrorCode;
import com.dcits.ftz.dto.in.UserIn;
import com.dcits.ftz.dto.out.UserOut;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Random;

@Service
public class DemoService {

    /**
     * 用户注册
     * <ul>
     *     <li>开启新事务，</li>
     *     <li></li>
     * </ul>
     *
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public UserOut register(UserIn userIn) {
        //TODO 用户入库
        final int idx = new Random().nextInt(5);
        userIn.setName("123456-" + idx);
        if (idx == 3) {
            throw new BusinessException(new ErrorCode("500001"), "这个地方出错了，报个业务错误");
        }
        final UserOut userOut = new UserOut();
        userOut.setUsername("wangwu" + idx);
        BeanUtils.copyProperties(userIn, userOut);
        //TODO 异步发送短信或邮件
        return userOut;
    }

}
